import * as fs from "node:fs";
import * as path from "node:path";

// 自定义插件：递归移动 sourcemap 文件
export const moveSourcesMap = {
  name: "move-sourcemaps", // 插件名
  closeBundle() {
    const distDir = path.resolve(process.cwd(), "dist");
    const sourcemapDir = path.resolve(distDir, "sourcemaps");

    // 如果 sourcemaps 文件夹不存在，则创建
    if (!fs.existsSync(sourcemapDir)) {
      fs.mkdirSync(sourcemapDir);
    }

    // 递归遍历 dist 目录，查找 .map 文件
    moveFiles(distDir, sourcemapDir).then(r => console.log(r));
  }
};

// 递归函数：遍历目录并移动文件
async function moveFiles(currentDir: string, sourcemapDir: string) {
  const files = await fs.promises.readdir(currentDir);

  for (const file of files) {
    const filePath = path.resolve(currentDir, file);
    const stats = await fs.promises.stat(filePath);

    if (stats.isDirectory()) {
      // 如果是文件夹，则递归调用
      await moveFiles(filePath, sourcemapDir);
    } else if (file.endsWith(".map")) {
      // 如果是 .map 文件，则移动
      const destinationPath = path.resolve(sourcemapDir, file);
      console.log(`Moving sourcemap: ${filePath} -> ${destinationPath}`);
      fs.renameSync(filePath, destinationPath); // 使用同步方法来移动文件
    }
  }
}
